<template>
  <div>
    <!-- 查询栏 -->
    <div class="toolbar">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-date-picker
            v-model="startDate"
            type="date"
            placeholder="开始日期"
            style="width: 100%">
          </el-date-picker>
        </el-col>
        <el-col :span="6">
          <el-date-picker
            v-model="endDate"
            type="date"
            placeholder="结束日期"
            style="width: 100%">
          </el-date-picker>
        </el-col>
        <el-col :span="6">
          <el-input placeholder="请输入小区名称" v-model="searchName"></el-input>
        </el-col>
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">查询</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-row>
    </div>

    <!-- 按钮区 -->
    <div class="button-bar">
      <el-button type="danger" icon="el-icon-delete" @click="handleBatchDelete">批量删除</el-button>
      <el-button type="primary" icon="el-icon-plus" @click="openAddDialog">添加</el-button>
    </div>

    <!-- 表格 -->
    <el-table :data="paginatedData" style="width: 100%" border
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="ID" prop="id"></el-table-column>
      <el-table-column label="所属小区" prop="districtName"></el-table-column>
      <el-table-column label="栋数" prop="buildingCode"></el-table-column>
      <el-table-column label="房产编码" prop="propertyCode"></el-table-column>
      <el-table-column label="房产名称" prop="propertyName"></el-table-column>
      <el-table-column label="户主名称" prop="ownerName"></el-table-column>
      <el-table-column label="联系电话" prop="contactNumber"></el-table-column>
      <el-table-column label="房间数" prop="roomCount"></el-table-column>
      <el-table-column label="单元" prop="unit"></el-table-column>
      <el-table-column label="楼层" prop="floor"></el-table-column>
      <el-table-column label="描述" prop="description" width="130"></el-table-column>
      <el-table-column label="入住时间" prop="moveInTime" width="130">
        <template #default="{ row }">
          {{ row.moveInTime ? formatDate(row.moveInTime) : '-' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="80">
        <template #default="{ row }">
          <i class="el-icon-edit" @click="editRow(row)"></i>
          <i class="el-icon-delete" @click="confirmDelete(row)"></i>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      background
      :current-page="currentPage"
      :page-size="pageSize"
      :total="filteredData.length"
      @current-change="handlePageChange"
      layout="total, prev, pager, next, jumper"
      style="margin-top: 20px; text-align: center;">
    </el-pagination>

    <!-- 删除确认弹窗 -->
    <el-dialog title="确认删除" :visible.sync="deleteDialogVisible" width="30%">
      <span>确定要删除该条数据吗？</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="deleteConfirmed">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 批量删除确认弹窗 -->
    <el-dialog title="确认批量删除" :visible.sync="batchDeleteDialogVisible" width="30%">
      <span>确定要删除选中的数据吗？</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchDeleteDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="batchDeleteConfirmed">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 无数据提示 -->
    <div v-if="filteredData.length === 0 && !isLoading" class="no-data">
      <p>暂无数据</p>
    </div>
    <update-property-dialog ref="addDialog" :editData="editData" :visible="visible" @submit="handleAddSubmit" @close="handleDialogClose"></update-property-dialog>
  </div>
</template>

<script>
import UpdatePropertyDialog from './UpdatePropertyDialog.vue';
import dayjs from 'dayjs';

export default {
  components: {
    UpdatePropertyDialog,
  },
  data() {
    return {
      startDate: '',
      endDate: '',
      searchName: '',
      currentPage: 1,
      pageSize: 5, // 每页显示5条数据
      selection: [],
      originalData: [
        // 添加一些初始数据进行测试
        {
          id: 1,
          districtName: '银华万庭',
          buildingCode: 'A栋',
          propertyCode: 'HM20191213002',
          propertyName: '金华小区A栋',
          ownerName: 'admin',
          contactNumber: '1111111111',
          roomCount: 4,
          unit: 3,
          floor: 22,
          description: '金华小区欢迎您',
          moveInTime: '2024-12-13'
        },
        {
          id: 2,
          districtName: '金华万庭',
          buildingCode: 'A栋',
          propertyCode: 'HM20191213001',
          propertyName: '金华小区',
          ownerName: '陈思语',
          contactNumber: '1111111111',
          roomCount: 4,
          unit: 3,
          floor: 22,
          description: '金华小区',
          moveInTime: '2019-12-13'
        }
      ],
      isLoading: false,
      deleteDialogVisible: false,
      batchDeleteDialogVisible: false,
      deleteRowId: null,
      visible: false,
      editData: null,
      dialogVisible: false,
    };
  },
  computed: {
    // 过滤后的数据
    filteredData() {
      if (!this.startDate && !this.endDate && !this.searchName) {
        return this.originalData;
      }
      return this.originalData.filter(item => {
        const matchesName = !this.searchName || item.districtName.includes(this.searchName);

        if (!this.startDate && !this.endDate) {
          return matchesName;
        }

        const itemDate = dayjs(item.moveInTime);
        const start = this.startDate ? dayjs(this.startDate) : null;
        const end = this.endDate ? dayjs(this.endDate) : null;

        const matchesStartDate = !start || itemDate.isSameOrAfter(start);
        const matchesEndDate = !end || itemDate.isSameOrBefore(end);

        return matchesName && matchesStartDate && matchesEndDate;
      });
    },

    // 当前页显示的数据
    paginatedData() {
      return this.filteredData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
    }
  },
  methods: {
    handlePageChange(page) {
      this.currentPage = page;
      this.selection = [];
    },
    handleSelectionChange(selection) {
      this.selection = selection;
    },
    editRow(row) {
      this.editData = row;
      this.visible = true;
      this.$refs.addDialog.openDialog();
    },
    confirmDelete(row) {
      this.deleteRowId = row.id;
      this.deleteDialogVisible = true;
    },
    deleteConfirmed() {
      if (this.deleteRowId !== null) {
        const index = this.originalData.findIndex(item => item.id === this.deleteRowId);
        if (index !== -1) {
          this.originalData.splice(index, 1);
          this.deleteDialogVisible = false;
          this.deleteRowId = null;
          this.$message.success('删除成功');
        }
      }
    },
    openAddDialog() {
      this.editData = null;
      this.visible = true;
      this.$refs.addDialog.openDialog();
      this.$refs.addDialog.resetForm(); // 重置表单数据
    },
    handleAddSubmit(formData) {
      if (this.editData) {
        // 编辑操作
        const index = this.originalData.findIndex(item => item.id === formData.id);
        if (index !== -1) {
          this.originalData.splice(index, 1, formData);
        }
      } else {
        // 添加操作
        const newId = Math.max(...this.originalData.map(item => item.id), 0) + 1;  // 生成新的ID
        formData.id = newId;
        // 生成唯一的房产编码
        const date = new Date();
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const nextNumber = this.originalData.length + 1;
        const propertyCode = `HM${year}${month}${day}${String(nextNumber).padStart(3, '0')}`;
        formData.propertyCode = propertyCode;
        this.originalData.unshift(formData);  // 添加到数据的顶部
      }
      this.$message.success('小区信息保存成功');
      this.visible = false;  // 关闭弹窗
    },
    handleCancel() {
      this.visible = false;  // 关闭弹窗
    },
    handleBatchDelete() {
      if (this.selection.length === 0) {
        this.$message.warning('请选择至少一项进行删除');
        return;
      }
      this.batchDeleteDialogVisible = true;
    },
    batchDeleteConfirmed() {
      const selectedIds = this.selection.map(item => item.id);
      this.originalData = this.originalData.filter(item => !selectedIds.includes(item.id));

      if ((this.currentPage - 1) * this.pageSize >= this.originalData.length && this.currentPage > 1) {
        this.currentPage--;
      }

      this.batchDeleteDialogVisible = false;
      this.selection = [];
      this.$message.success('批量删除成功');
    },
    handleSearch() {
      this.isLoading = true;

      // 模拟API请求延迟
      setTimeout(() => {
        this.currentPage = 1; // 重置页码
        this.isLoading = false;

        if (this.filteredData.length === 0) {
          this.$message.info('没有找到匹配的数据');
        }
      }, 800);
    },
    resetSearch() {
      this.startDate = '';
      this.endDate = '';
      this.searchName = '';
      this.currentPage = 1;
      this.selection = [];
    },
    handleDialogClose() {
      this.editData = null;
      this.visible = false;
    },
    formatDate(date) {
      return dayjs(date).format('YYYY-MM-DD');
    }
  }
};
</script>

<style scoped lang="scss">
.toolbar {
  margin-bottom: 20px;
}

.toolbar .el-row {
  margin-bottom: 10px;
}

.button-bar {
  background-color: #F2F2F2;
  padding: 6px 10px;
  margin-bottom: 20px;
}

.el-button {
  margin-right: 10px;
}

.el-table {
  border: 1px solid #dcdfe6;
  margin-top: 10px;
}

.el-table th, .el-table td {
  padding: 8px 10px;
}

.el-table th {
  background-color: #f2f2f2;
  color: #333333;
  font-weight: bold;
}

.el-table thead{
  color:#333333;
}

.el-table td {
  border-bottom: 1px solid #dcdfe6;
}

.el-pagination {
  margin-top: 20px;
  text-align: center;
}

.el-icon-edit:hover {
  cursor: pointer;
  color: #2A6496;
}
.el-icon-delete:hover{
  cursor: pointer;
  color: #2A6496;
}
.el-icon-edit{
  margin-right: 8px;
}

.no-data {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px;
  color: #999;
}

.no-data img {
  width: 150px;
  height: 150px;
  margin-bottom: 20px;
  opacity: 0.5;
}
</style>